#!/usr/bin/env python2.6
# -*- coding: utf-8 -*-

import logging
import urllib
import urllib2
import json

API_ENDPOINT = 'https://readitlaterlist.com/v2/'

class ReadItLaterError(Exception): pass
class RequestError(ReadItLaterError): pass
class AuthError(ReadItLaterError): pass
class RateLimitExceeded(ReadItLaterError): pass
class ServerError(ReadItLaterError): pass

class API(object):
    def __init__(self, api_key):
        self.__status = None
        self.api_key = api_key

    def __call(self, method, **params):
        params['apikey'] = self.api_key
        params = dict([(k, v) for k, v in params.items() if v])
        try:
            res = urllib2.urlopen("%s%s?%s" % (
                API_ENDPOINT, method, urllib.urlencode(params)))
            logging.debug(res.url)
            self.__status = {
                    'User-Limit': res.headers.get('X-Limit-User-Limit'),
                    'User-Remaining': res.headers.get('X-Limit-User-Remaining'),
                    'User-Reset': res.headers.get('X-Limit-User-Reset'),
                    'Key-Limit': res.headers.get('X-Limit-Key-Limit'),
                    'Key-Remaining': res.headers.get('X-Limit-Key-Remaining'),
                    'Key-Reset': res.headers.get('X-Limit-Key-Reset'), }
            logging.debug(self.__status)
            return res.read()
        except urllib2.URLError, e:
            logging.debug(e.url)
            logging.error(e)

            if e.code == 400:
                raise RequestError("Invalid request, please make sure "
                        "you follow the documentation for proper syntax")
            elif e.code == 401:
                raise AuthError("Username and/or password is incorrect")
            elif e.code == 403:
                raise RateLimitExceeded("Rate limit exceeded, please "
                        "wait a little bit before resubmitting")
            elif e.code == 503:
                raise ServerError("Read It Later's sync server is down "
                        "for scheduled maintenance")
            else:
                raise ReadItLaterError("Unknown error occurred while "
                        "requesting readitlater")

    def auth(self, username, password):
        self.__call('auth', username=username, password=password)
        return True

    def add(self, username, password, url, title=None):
        self.__call('add', username=username, password=password,
                url=url, title=title)
        return True

    def send(self, username, password, **params):
        """
        Send changes using the `send` method

        See more about this API here:
        http://readitlaterlist.com/api/docs/#send

        Examples
        --------

        >>> new = [
        ...     {"url":"http://google.com",
        ...      "title":"Google"
        ...      "ref_id":"123456709"
        ...      },
        ...      {"url":"http://ideashower.com"
        ...       "title":"The Idea Shower"
        ...      },
        ... ]
        >>> api.send(username, password, new=new)

        """
        jsonparams = dict(
            (key, json.dumps(
                dict((str(i), val) for (i, val) in enumerate(vallist))))
            for (key, vallist) in params.iteritems())
        self.__call('send', username=username, password=password, **jsonparams) #IGNORE:W0142
        return True

    def get(self, username, password, **params):
        """
            Hecho por mi segun esto: http://readitlaterlist.com/api/docs/#get
        """
        jsonparams = dict(
            (key, json.dumps(
                dict((str(i), val) for (i, val) in enumerate(vallist))))
            for (key, vallist) in params.iteritems())
        return self.__call('get', username=username, password=password, **jsonparams) #IGNORE:W0142


    def status(self):
        if not self.__status:
            self.__call('api')
        return self.__status

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)